package com.example.chirdrenserver.Service.AdminService.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chirdrenserver.Pojo.dto.admin.AdminUserQueryDTO;
import com.example.chirdrenserver.Pojo.entity.User;
import com.example.chirdrenserver.Pojo.entity.UserRole;
import com.example.chirdrenserver.Service.AdminService.UserRoleService;
import com.example.chirdrenserver.Service.AdminService.UserService;
import com.example.chirdrenserver.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service("adminUserService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserRoleService userRoleService;

    @Autowired
    public UserServiceImpl(UserRoleService userRoleService) {
        this.userRoleService = userRoleService;
    }

    @Override
    public IPage<User> getUserPage(AdminUserQueryDTO queryDTO) {
        // 获取分页参数
        long current = queryDTO.getCurrentPage() != null ? queryDTO.getCurrentPage() : 1L;
        long size = queryDTO.getPageSize() != null ? queryDTO.getPageSize() : 15L;

        Page<User> page = new Page<>(current, size);
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        // 添加查询条件
        if (StringUtils.hasText(queryDTO.getEmail())) {
            wrapper.eq("email", queryDTO.getEmail());
        }
        if (StringUtils.hasText(queryDTO.getNickname())) {
            wrapper.like("nickname", queryDTO.getNickname());
        }
        if (queryDTO.getSex() != null) {
            wrapper.eq("sex", queryDTO.getSex());
        }

        // 添加排序
        if (StringUtils.hasText(queryDTO.getSortField())) {
            wrapper.orderBy(true,
                    "asc".equalsIgnoreCase(queryDTO.getSortOrder()),
                    queryDTO.getSortField());
        } else {
            wrapper.orderByDesc("create_time");
        }

        return baseMapper.selectPage(page, wrapper);
    }

    @Override
    public User getUserById(Long userId) {
        return getById(userId);
    }

    @Override
    public User getUserByEmail(String email) {
        return baseMapper.findByEmail(email);
    }

    @Override
    public List<User> searchByNickname(String nickname) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("nickname", nickname);
        return list(wrapper);
    }

    @Override
    public List<User> list() {
        return baseMapper.selectList(new QueryWrapper<User>().orderByDesc("create_time"));
    }

    @Override
    public User getUserByNickname(String nickname) {
        return query().eq("nickname", nickname).one();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long userId) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        userRoleService.remove(wrapper);
        return this.removeById(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignRoles(Long userId, List<Integer> roleIds) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        userRoleService.remove(wrapper);

        for (Integer roleId : roleIds) {
            if (roleId != null) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleService.save(userRole);
            }
        }
        return true;
    }

    @Override
    public List<Integer> getUserRoleIds(Long userId) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).select("role_id");
        return userRoleService.list(wrapper).stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
    }

    @Override
    public Map<Long, List<Integer>> getUserRoleIdsBatch(List<Long> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return new HashMap<>();
        }

        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", userIds);
        List<UserRole> userRoles = userRoleService.list(wrapper);

        return userRoles.stream()
                .collect(Collectors.groupingBy(
                        UserRole::getUserId,
                        Collectors.mapping(UserRole::getRoleId, Collectors.toList()))
                );
    }
}